#include <iostream>
using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* cur1 = l1, *cur2 = l2;
        ListNode* newhead = new ListNode, *tail = newhead;
        int carry = 0;
        while (cur1 || cur2 || carry) 
        {
            int add1 = 0;
            if (cur1)
            {
                add1 = cur1->val;
                cur1 = cur1->next;
            }
            int add2 = 0;
            if (cur2)
            {
                add2 = cur2->val;
                cur2 = cur2->next;
            }
            int sum = add1 + add2 + carry;
            carry = sum / 10;
            int res = sum % 10;
            ListNode* tmp = new ListNode(res);
            if (newhead == tail)
            {
                newhead->next = tmp;
                tail = tail->next;
            }
            else
            {
                tail->next = tmp;
                tail = tail->next;
            }
        }
        ListNode* ret = newhead->next;
        delete newhead;

        return ret;
    }
};

